<?php
include_once "db_config.php";
class DbModel{
	
	public $connection;
	public function __construct(){
		
		// create mysql connection and related stuff
		$this->connection = mysql_connect(DB_SERVER . ":" . DB_PORT, DB_USER, DB_PASS) or die("Error connecting to DB server");
		mysql_select_db(DB_DATABASE) or die("Database not found.");
		mysql_query("SET NAMES " . DB_ENCODING);
		
		// init stuff
		if (!$this->table_name){
			$this->table_name = preg_replace('/^db_/', '', class2file(get_class($this)));
		}
		if(!$this->order){
			$this->order = "id";
		}
	}
	
	private function _parseOptions($options){
		// SELECT
		$sql_select = "SELECT *";
		if($options["select"]){
			$sql_select = "SELECT " . is_array($options["select"]) ? implode(", ", $options["select"]) : $options["select"];
		}
		
		// FROM
		$sql_from = "FROM " . $this->table_name;
		
		// WHERE
		$sql_where = "";
		if ($options["conditions"]){
			$sql_where = "WHERE " . is_array($options["conditions"]) ? implode(" AND ", $options["conditions"]) : $options["conditions"];
		}
		
		// GROUP
		$sql_group = "";
		if($options["group"]){
			$sql_group = "GROUP BY " . is_array($options["group"]) ? implode(", ", $options["group"]) : $options["group"];
		}
		
		// ORDER
		$sql_order = "ORDER BY " . $this->order;
		if($options["order"]){
			$sql_group = "ORDER BY " . is_array($options["order"]) ? implode(", ", $options["order"]) : $options["order"];
		}
		
		// LIMIT
		$sql_limit = "";
		if($options["offset"]){
			if (!is_array($options["offset"])){
				$options["offset"] = array($options["offset"]);
			}
			$per_page = isset($options["offset"][1]) ? (int)$options["offset"][1] : ITEMS_PER_PAGE;
			$start = ((int)$options["offset"][0] - 1) * $per_page;
			$sql_limit = "LIMIT $start, $per_page";
		}
		
		return "$sql_select $sql_from $sql_where $sql_group $sql_order $sql_limit";
	}
	
	private function _query($options){
		$sql = $this->_parseOptions($options);
		
		$ret = false;
		if($res = mysql_query($sql)){
			$ret = array();
			while($r = mysql_fetch_assoc($res)){
				$ret[] = $r;
			}
		}
		
		if($ret === false){
			Logger::add("Query: \"$sql\" triggered following error: " . mysql_errno() . "# " . mysql_error() . "\r\n");
			$ret = array();
		}
		
		return $ret;
	}
	
	public function find($options=array()){
		return $this->_query($options);
	}
	public function row($options=array()){
		$options["offset"] = array(0, 1);
		list($ret) = $this->_query($options);
		return count($ret)>0 ? $ret : array();
	}
	public function field($field, $options=array()){
		$row = $this->row($options);
		return $row[$field];
	}
	
}